
package com.apiserver.kernel.utils;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

import static org.apache.commons.codec.binary.Hex.decodeHex;

public class SignUtil {
	
	/**
	 * BCC签名验证
	 * 
	 * @param content   原始数据
	 * @param sign      十六进制签名数据
	 * @param publicKey 十六进制公钥
	 * @return
	 */
	public static boolean verify(String content, String sign, String publicKey) {
		try {
			Signature signature = Signature.getInstance("MD5withRSA");
			signature.initVerify(generatePublicKey(decodeHex(publicKey.toCharArray())));
			signature.update(content.getBytes());
			if (signature.verify(decodeHex(sign.toCharArray()))) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * BCC生成公钥
	 * 
	 * @param encodedKey
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	public static PublicKey generatePublicKey(byte[] encodedKey)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
	}
}
